import * as TYPES from "../action-types";
import {
  getDjRadioCatelist,
  getDjRadioRecommend,
  getDjRadios,
} from "services/diradio";

let actions = {
  getRadCateList: async () => {
    const { categories } = await getDjRadioCatelist();
    return (dispatch) => {
      dispatch({
        type: TYPES.RAD_CATEGORIES,
        payload: categories,
      });
      dispatch(actions.setCurrentId(categories[0].id));
    };
  },
  setCurrentId: (id) => {
    return (dispatch, getState) => {
      const currentId = getState().getIn(["djradio", "currentId"]);
      if (currentId === id) return;
      dispatch({
        type: TYPES.RAD_CHANGE_ID,
        payload: id,
      });
      dispatch(actions.getRadioRe(id));
      dispatch(actions.getRadioRank({ cateId: id }));
    };
  },
  getRadioRe: async (id) => {
    const res = await getDjRadioRecommend({ type: id });
    return {
      type: TYPES.RAD_RECOMMENDS,
      payload: res.djRadios,
    };
  },
  getRadioRank: ({ cateId = -1, limit = 24, offset = 1 }) => {
    return async (dispatch, getState) => {
      const currentId = getState().getIn(["djradio", "currentId"]);
      if (cateId === -1) {
        cateId = currentId;
      }
      const res = await getDjRadios({ cateId, limit, offset });
      const { djRadios, count } = res;
      dispatch({
        type: TYPES.RAD_RADIOS,
        payload: { djRadios, count },
      });
    };
  },
};

export default actions;
